//
//  IAAAuthCheckDetailVC.m
//  iPadAuditAuthorise
//
//  Created by XiangDongMBP on 16/9/7.
//  Copyright © 2016年 XiangDong. All rights reserved.
//

#import "IAAAuthCheckDetailVC.h"
#import "IAAAuthCheDetailTCell.h"
#import "IAAAuthCheDetailCCell.h"
#import "GlobalHeader.h"
#import <UITableView+FDTemplateLayoutCell.h>
#import "IAAAuthCheckModel.h"
#import <YYWebImage.h>
#import "XDEmptyVCView.h"
#import "IAAAuthCheckSureVC.h"
#import "IAAAuthCheSecCheckerVC.h"
#import <MWPhotoBrowser.h>
#import "SDPhotoBrowser.h"
#import "SDBrowserImageView.h"
#import "IAAAuthCheComCCell.h"
#import "IAAAuthCheckZoomVC.h"

@interface IAAAuthCheckDetailVC ()<MWPhotoBrowserDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, XDEmptyVCViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, IAAAuthCheDetailCCellDelegate, IAAAuthCheComCCellDelegate, SDPhotoBrowserDelegate>

@property (weak, nonatomic) IBOutlet UIView *upBgView;

@property (weak, nonatomic) IBOutlet UILabel *deviceNoLabel;
@property (weak, nonatomic) IBOutlet UILabel *busiNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *fstStateLabel;
@property (weak, nonatomic) IBOutlet UILabel *fstReasonLabel;

@property (weak, nonatomic) IBOutlet UICollectionView *centerCollectionView;
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;
@property (weak, nonatomic) IBOutlet UICollectionView *sideCollectionView;

@property (weak, nonatomic) IBOutlet UIButton *sureBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *sureBtnCenterXConstraint;
@property (weak, nonatomic) IBOutlet UIButton *backTaskBtn;

@property (strong, nonatomic) XDEmptyVCView *emptyView;

@property (assign, nonatomic) NSInteger curIndex;       //!< 当前拍照的界面是添加到那个image
@property (strong, nonatomic) NSArray<NSDictionary *> *imgInfoEnumArray; //!< 拍照时文件类型的枚举
@property (assign, nonatomic) NSInteger imgInfoIndex;   //!< 拍照时文件类型的标记
@property (strong, nonatomic) IAAAuthCheckCommitModel *commitModel;

@end

static NSString * const reuseTCellId = @"IAAAuthCheDetailTCell";
static NSString * const reuseCCellId = @"IAAAuthCheDetailCCell";
static NSString * const reuseComCCellId = @"IAAAuthCheComCCell";

@implementation IAAAuthCheckDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initLogicData];
    //设置导航栏
    [self initNavigationBar];
    //設置子Views
    [self initSubViews];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    NSLog(@"%s", __FUNCTION__);
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)initLogicData {
    self.commitModel = [[IAAAuthCheckCommitModel alloc] initWithAuChTaskItem:self.taskItem];
    self.commitModel.orgNo = IAA_APP_DELEGATE.organizeId;
    self.commitModel.userNo = IAA_APP_DELEGATE.userNo;
    self.commitModel.token = IAA_APP_DELEGATE.token;
//    self.taskItem.taskLevel = 11;
    
    // 首先整理数据
    [self.model changeFalseData];
    [self.model toSortImageList];
}

- (NSInteger)imgInfoIndexOfFileName:(NSString *)fileName {
    __block NSInteger index = 0;
    [self.imgInfoEnumArray enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj[@"fileName"] isEqualToString:fileName]) {
            index = idx;
            *stop = YES;
        }
    }];
    return index;
}

- (void)initNavigationBar {
    self.navigationItem.title = @"业务审核信息";
}

- (void)initSubViews {
    self.upBgView.layer.borderWidth = 1;
    self.upBgView.layer.borderColor = [IAA_COLOR_0xE0E0E0(1.0) CGColor];
    
    UINib *cCellNib = [UINib nibWithNibName:reuseCCellId bundle:nil];
    [self.sideCollectionView registerNib:cCellNib forCellWithReuseIdentifier:reuseCCellId];
    UINib *comCellNib = [UINib nibWithNibName:reuseComCCellId bundle:nil];
    [self.sideCollectionView registerNib:comCellNib forCellWithReuseIdentifier:reuseComCCellId];
    self.sideCollectionView.backgroundColor = [UIColor whiteColor];
    self.sideCollectionView.delegate = self;
    self.sideCollectionView.dataSource = self;
    
    [self.centerCollectionView registerNib:cCellNib forCellWithReuseIdentifier:reuseCCellId];
    [self.centerCollectionView registerNib:comCellNib forCellWithReuseIdentifier:reuseComCCellId];
    self.centerCollectionView.backgroundColor = [UIColor whiteColor];
    self.centerCollectionView.delegate = self;
    self.centerCollectionView.dataSource = self;
    
    self.sureBtn.layer.cornerRadius = 3;
    self.sureBtn.layer.masksToBounds = YES;
    self.backTaskBtn.layer.cornerRadius = 3;
    self.backTaskBtn.layer.masksToBounds = YES;
    [self.sureBtn addTarget:self action:@selector(sureBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.backTaskBtn addTarget:self action:@selector(backTaskBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    if (self.taskItem.taskLevel == 12) { // 二审
        self.sureBtnCenterXConstraint.constant = 0;
        self.backTaskBtn.hidden = YES;
    }
    
    self.emptyView = [[[NSBundle mainBundle] loadNibNamed:@"XDEmptyVCView" owner:self options:nil] firstObject];
    self.emptyView.delegate = self;
    
    [self requestAuthCheckDetail];
    [self refreshWholeView];
}

- (void)refreshWholeView {
    
    self.deviceNoLabel.text = self.model.deviceNo;
    self.busiNameLabel.text = self.model.busiName;
    self.fstStateLabel.text = self.model.fstState;
    self.fstReasonLabel.text = self.model.fstReason;
    
    self.pageControl.numberOfPages = self.model.sortImgList.count;
//    self.pageControl.currentPage = ;
    
    [self.centerCollectionView reloadData];
    [self.sideCollectionView reloadData];
}

#pragma mark - <GGBannerViewDelegate>代理
//-(void)bannerView:(GGBannerView *)bannerView didSelectAtIndex:(NSUInteger)index {
////    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
////    browser.displayActionButton = NO;
////    [self.navigationController pushViewController:browser animated:YES];
////    [browser setCurrentPhotoIndex:index];
//    
//    SDPhotoBrowser *photoBrowser = [SDPhotoBrowser new];
//    photoBrowser.delegate = self;
//    photoBrowser.currentImageIndex = index;
//    photoBrowser.imageCount = self.model.imgelist.count;
//    photoBrowser.sourceImagesContainerView = bannerView;
//    
//    [photoBrowser show];
//}

#pragma mark - <UICollectionViewDelegateFlowLayout>代理
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.sideCollectionView) {
        return CGSizeMake(159.0f, 127.0f);
    } else {
        return collectionView.bounds.size;
    }
}

#pragma mark - <UICollectionViewDelegate>代理
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.sideCollectionView) {
        if (indexPath.row < self.model.sortImgList.count) {
            [self.centerCollectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        } else {
            UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
            [self selImgFileTypeBeforPhoto:cell];
        }
    } else {
        IAAAuthCheckZoomVC *vc = [[IAAAuthCheckZoomVC alloc] init];
        vc.model = self.model;
        vc.index = indexPath.row;
        vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        [self presentViewController:vc animated:YES completion:nil];
    }
}

#pragma mark - <UICollectionViewDataSource>代理
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.taskItem.taskLevel == IAAAuChTaskLevelSecond || collectionView == self.centerCollectionView) {
        return self.model.sortImgList.count;   // 二审不允许补拍or大图原始大小显示
    }
    
    return (self.model.canAddNum > 0) ? self.model.sortImgList.count + 1 : self.model.sortImgList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.centerCollectionView) {
        self.pageControl.currentPage = indexPath.row;
    }
    
    IAAAuthCheckSortItem *sortItem = nil;
    if (indexPath.row < self.model.sortImgList.count) {
        sortItem = self.model.sortImgList[indexPath.row];
        if (sortItem.imgArray.count > 1) {
            IAAAuthCheComCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseComCCellId forIndexPath:indexPath];
            
            IAAAuthCheComCCellType type = (collectionView == self.sideCollectionView) ? IAAAuthCheComCCellTypeCircle : IAAAuthCheComCCellTypeRect;
            [cell configViewWithData:self.model sortItem:sortItem type:type];
            cell.delegate = self;
            return cell;
        }
    }
    
    // 单独 or +号
    IAAAuthCheDetailCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseCCellId forIndexPath:indexPath];
    IAAAuthCheDetailCCellType type = (collectionView == self.sideCollectionView) ? IAAAuthCheDetailCCellTypeCircle : IAAAuthCheDetailCCellTypeRect;
    [cell configViewWithData:sortItem type:type];
    cell.delegate = self;
    return cell;
}

#pragma mark -<IAAAuthCheDetailCCellDelegate>代理
- (void)IAAAuthCheDetailCCell:(IAAAuthCheDetailCCell *)cell closeBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.sideCollectionView indexPathForCell:cell];
    IAAAuthCheckSortItem *sortItem = self.model.sortImgList[indexPath.row];
    [self.model.imgelist removeObjectsInArray:sortItem.imgArray];
    [self.model toSortImageList];   //减少之后也要重新整理
    [self refreshWholeView];
}
- (void)IAAAuthCheDetailCCell:(IAAAuthCheDetailCCell *)cell cameraBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.centerCollectionView indexPathForCell:cell];
    IAAAuthCheckSortItem *sortItem = self.model.sortImgList[indexPath.row];
    self.curIndex = [self.model.imgelist indexOfObject:[sortItem.imgArray firstObject]];
    [self takePhoto];
}
#pragma mark - <IAAAuthCheComCCellDelegate>代理
- (void)IAAAuthCheComCCell:(IAAAuthCheComCCell *)cell cameraBtnTapped:(NSInteger)index {
    NSIndexPath *indexPath = [self.centerCollectionView indexPathForCell:cell];
    IAAAuthCheckSortItem *sortItem = self.model.sortImgList[indexPath.row];
    self.curIndex = [self.model.imgelist indexOfObject:sortItem.imgArray[index]];
    [self takePhoto];
}

#pragma mark - <UIImagePickerControllerDelegate>代理
- (void)selImgFileTypeBeforPhoto:(UIView *)source {
//    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"选择图像类型"
//                                                                     message:nil
//                                                              preferredStyle:UIAlertControllerStyleActionSheet];
//    for (NSDictionary *dic in self.imgInfoEnumArray) {
//        [alertVC addAction:[UIAlertAction actionWithTitle:dic[@"fileName"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            self.imgInfoIndex = [self imgInfoIndexOfFileName:action.title];
//            [self takePhoto];
//        }]];
//    }
//    UIPopoverPresentationController *popover = alertVC.popoverPresentationController;
//    if (popover){
//        popover.sourceView = source;
//        popover.sourceRect = source.bounds;
//        popover.permittedArrowDirections = UIPopoverArrowDirectionRight;
//    }
//    [self presentViewController:alertVC animated:YES completion:nil];
    
    self.curIndex = self.model.imgelist.count;  //增加的index = count
    [self takePhoto];
}
- (void)takePhoto {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    NSData *data = UIImageJPEGRepresentation(image, IAA_JPEG_QUALITY);
    NSString *base64 = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    if (self.curIndex < self.model.imgelist.count) {
        IAAAuthCheckImgItem *item = self.model.imgelist[self.curIndex];
        item.isReplace = YES;
        item.needUpload = YES;
        item.imageBase64 = base64;
        item.fileFormat = @"jpg";
        item.fileSize = [data length];
        NSLog(@"新增图片的base64长度%zd，字节长度%zd", base64.length, [data length]);
    } else {
        IAAAuthCheckImgItem *item = [[IAAAuthCheckImgItem alloc] init];
        item.isReTakePicture = YES; // 允许再次补拍
        item.isAdd = YES;           // 标记是新增的(可以删除)
        item.needUpload = YES;      // 标记需要上传
        item.imageBase64 = base64;
        item.fileFormat = @"jpg";
        item.fileSize = [data length];
        item.imageName = @"其他证件";
        item.imageType = 99;
        [self.model.imgelist addObject:item];
        [self.model toSortImageList];   //增加之后要重新整理显示数据
        NSLog(@"新增图片的base64长度%zd，字节长度%zd", base64.length, [data length]);
    }
    [self dismissViewControllerAnimated:YES completion:^{
        [self refreshWholeView];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - <XDEmptyVCViewDelegate>代理
- (void)xDEmptyVCView:(XDEmptyVCView *)selPhotoView refreshBtnTapped:(UIButton *)btn {
    [self requestAuthCheckDetail];
}

#pragma mark - <MWPhotoBrowserDelegate>代理
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return self.model.imgelist.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    IAAAuthCheckImgItem *item = self.model.imgelist[index];
    
    
    __block MWPhoto *photo = [MWPhoto photoWithImage:[UIImage imageWithData:[self.model imageDataWithIndex:index]]];
    photo.caption = item.imageName;
    
    if (item.ufid.length && !item.imageBase64.length) {
        NSString *requestStr = [IAAUrlProtocolMerge appFileImgQueryImg];
        NSDictionary *pars = @{@"ufid"   : item.ufid,
                               @"osName" : @"iOS",
                               @"token"  : IAA_APP_DELEGATE.token};
        [XDAFHttpRequest POST:requestStr parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"resultCode"] isEqualToString:IAA_RESULT_CODE_SUC]) {
                item.imageBase64 = responseObject[@"imageBase64"];
                photo = [MWPhoto photoWithImage:[UIImage imageWithData:[self.model imageDataWithIndex:index]]];
                photo.caption = item.imageName;
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            ;
        }];
    }

    return photo;
}

#pragma mark - <SDPhotoBrowserDelegate>代理
- (void)photoBrowser:(SDPhotoBrowser *)browser imageView:(SDBrowserImageView *)imageView placeholderImgForIndex:(NSInteger)index {
    imageView.image = [UIImage imageWithData:[self.model imageDataWithIndex:index]];
    
    IAAAuthCheckImgItem *item = self.model.imgelist[index];
    if (item.ufid.length && !item.imageBase64.length) {
        NSString *requestStr = [IAAUrlProtocolMerge appFileImgQueryImg];
        NSDictionary *pars = @{@"ufid"   : item.ufid,
                               @"osName" : @"iOS",
                               @"token"  : IAA_APP_DELEGATE.token};
        
//        [imageView addWaitingView]; //增加进度条
        
        [XDAFHttpRequest POST:requestStr parameters:pars progress:^(NSProgress * _Nonnull uploadProgress) {
            dispatch_async(dispatch_get_main_queue(), ^{
                imageView.progress = uploadProgress.fractionCompleted;
            });
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [imageView removeWaitingView];
            if ([responseObject[@"resultCode"] isEqualToString:IAA_RESULT_CODE_SUC]) {
                item.imageBase64 = responseObject[@"imageBase64"];
                imageView.image = [UIImage imageWithData:[self.model imageDataWithIndex:index]];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [imageView removeWaitingView];
        }];
    }
}

#pragma mark - 按键处理
- (void)sureBtnTapped:(UIButton *)btn {
    IAAAuthCheckSureVC *vc = [[IAAAuthCheckSureVC alloc] init];
    vc.commitModel = self.commitModel;
    vc.taskItem = self.taskItem;
    vc.auChModel = self.model;
    vc.auChSureHandle = ^(AuChSureResult result){
        if (result == AuChSureResultClose) {
            [self refreshWholeView];
        } else {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    };
    UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:vc];
    navVC.modalPresentationStyle = UIModalPresentationFormSheet;
    [self presentViewController:navVC animated:YES completion:nil];
}

- (void)backTaskBtnTapped:(UIButton *)btn {
    [self askToAbandonTask];
}

- (void)askToAbandonTask {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"是否取消该笔业务审核？" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self requestAbandonTask];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 网络请求
- (void)requestAuthCheckDetail {
//    NSString *urlStr = [IAAUrlProtocolMerge appAuthCheckTaskDetail];
//    NSDictionary *pars = @{@"orgNo"  : IAA_APP_DELEGATE.organizeId,
//                           @"userNo" : IAA_APP_DELEGATE.userNo,
//                           @"token"  : IAA_APP_DELEGATE.token,
//                           @"osName" : @"iOS",
//                           @"busiId" : self.taskItem.busiId,
//                           @"taskId" : @(self.taskItem.taskId)};
//    
//    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    [XDAFHttpRequest POST:urlStr parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"业务审核详情返回%@", responseObject);
//        [hud hide:NO];
//        self.model = [IAAAuthCheckDetailModel yy_modelWithJSON:responseObject];
//        [self.model changeFalseData];
//        [self.model toSortImageList];
//        if ([self.model.resultCode isEqualToString:IAA_RESULT_CODE_SUC]) {
//            [self refreshWholeView];
//            [self.emptyView hide];
//        }else{
//            [MBProgressHUD showPromptWithAutoHideInView:self.view message:self.model.resultMsg];
//            [self.emptyView showInView:self.view];
//        }
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"业务审核详情失败%@", error);
//        [hud hide:NO];
//        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
//        [self.emptyView showInView:self.view];
//    }];
}

// 返回任务池
- (void)requestAbandonTask {
    NSString *urlStr = [IAAUrlProtocolMerge appAuthCheckAbandonTask];
    NSDictionary *pars = @{@"busiId" : self.taskItem.busiId,
                           @"taskId" : @(self.taskItem.taskId),
                           @"osName" : @"iOS",
                           @"token"  : IAA_APP_DELEGATE.token};
    
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.parentViewController.view animated:YES];
    [XDAFHttpRequest POST:urlStr parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [hud hide:NO];
        NSLog(@"返回任务池请求返回%@", responseObject);
        if ([responseObject[@"resultCode"] isEqualToString:IAA_RESULT_CODE_SUC]) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }else{
            [MBProgressHUD showPromptWithAutoHideInView:self.parentViewController.view message:responseObject[@"resultMsg"]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"返回任务池请求失败%@", error);
        [hud hide:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.parentViewController.view message:@"网络请求失败"];
    }];
}

@end
